//
//  AppDelegate.m
//  Yimei
//
//  Created by xiaowu xiaowu on 2017/10/19.
//  Copyright © 2017年 xiaowu xiaowu. All rights reserved.
//

#import "AppDelegate.h"
#import <AlipaySDK/AlipaySDK.h>
#import "TPShare.h"
#import "TPLoginViewController.h"
#import "YPGuidePageCollectionViewController.h"
@interface AppDelegate ()<CLLocationManagerDelegate>
@property (nonatomic,strong)CLLocationManager *locationManager;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self setup];
    [self findCurrentLocation];
    [TPShare registWithShare];
    
//    self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[TPLoginViewController new]];
    return YES;
}

-(void)setup{
    [UINavigationBar appearance].barStyle  = UIBarStyleDefault;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    //    [[UINavigationBar appearance] setClipsToBounds:YES]; //去掉setShadowImage
    [[UINavigationBar appearance] setShadowImage:[UIImage new]];
    //     [[UINavigationBar appearance] setShadowImage:[UIImage imageWithColor:COLORRGB(240.0, 240.0, 240.0)]];
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageWithColor:TPAllBackgroundColor]  forBarMetrics:UIBarMetricsDefault];
    
    BOOL isGuide = [[NSUserDefaults standardUserDefaults]boolForKey:@"YPGuidePageCollectionViewController"];
    if(isGuide)
        return;
    
    YPGuidePageCollectionViewController *pageVC = [YPGuidePageCollectionViewController new];
    self.window.rootViewController = pageVC;
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"YPGuidePageCollectionViewController"];
    
//    [[UISearchBar appearance] setSearchFieldBackgroundImage:[self searchFieldBackgroundImage] forState:UIControlStateNormal];
    
}
//调用方法
- (UIImage*)searchFieldBackgroundImage {
    UIColor*color = [UIColor whiteColor];
    CGFloat cornerRadius = 5;
    CGRect rect =CGRectMake(0,0,28,28);
    
    UIBezierPath*roundedRect = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
    roundedRect.lineWidth=0;
    
    UIGraphicsBeginImageContextWithOptions(rect.size,NO,0.0f);
    [color setFill];
    [roundedRect fill];
    [roundedRect stroke];
    [roundedRect addClip];
    
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(void)netWork{
    
    //监听网络状态
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
            }
                break;
            case   AFNetworkReachabilityStatusNotReachable: {
                
                //  [[[UIAlertView alloc]initWithTitle:@"网络不稳定,请检查" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
            }
                break;
            default:
                break;
                
        }
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [TPShare handleOpenURL:url];
}

#ifdef __IPHONE_9_0
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url
                                                  standbyCallback:^(NSDictionary *resultDic) {
                                                      DLog(@"result = %@",resultDic);
                                                      if ([OpenShare paySuccessCallback]) {
                                                          [OpenShare paySuccessCallback](resultDic);
                                                      }
                                                  }];
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            //            NSString *result = resultDic[@"result"];
            if ([OpenShare paySuccessCallback]) {
                [OpenShare paySuccessCallback](resultDic);
            }
            //            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
        
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            DLog(@"result = %@",resultDic);
            if ([OpenShare paySuccessCallback]) {
                [OpenShare paySuccessCallback](resultDic);
            }
            
        }];
    }
    
    
    return [TPShare handleOpenURL:url];
}
#else
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    
    
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url
                                                  standbyCallback:^(NSDictionary *resultDic) {
                                                      DLog(@"result = %@",resultDic);
                                                      if ([OpenShare paySuccessCallback]) {
                                                          [OpenShare paySuccessCallback](resultDic);
                                                      }
                                                  }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            //            NSString *result = resultDic[@"result"];
            if ([OpenShare paySuccessCallback]) {
                [OpenShare paySuccessCallback](resultDic);
            }
            //            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            DLog(@"result = %@",resultDic);
            if ([OpenShare paySuccessCallback]) {
                [OpenShare paySuccessCallback](resultDic);
            }
            //            [UIView dismiss_progress];
        }];
    }
    
    
    
    return [TPShare handleOpenURL:url];
    
}
#endif
- (void)findCurrentLocation {
    
    self.locationCity = @"广州市";
    //    return;
    _locationManager = [[CLLocationManager alloc]init];
    _locationManager.delegate = self;
    
    // 1
    if (! [CLLocationManager locationServicesEnabled]) {
        [UIAlertView alertWithCallBackBlock:^(NSInteger buttonIndex) {
            ;
        } title:@"未开启定位服务" message:@"请开启定位服务定位您所在城市." cancelButtonName:@"确定" otherButtonTitles:nil, nil];
        
    }
    // 2
    else if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
    }
    // 3
    else {
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    
    // 5
    CLLocation *newLocation = [locations lastObject];
    DLog(@"latitude === %g  longitude === %g",newLocation.coordinate.latitude, newLocation.coordinate.longitude);
    self.coordnate = newLocation.coordinate;
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    // 反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (! error) {
            
            if ([placemarks count] > 0) {
                
                CLPlacemark *placemark = [placemarks firstObject];
                NSString *city = placemark.locality;  // 获取城市
                if (! city) {
                    city = placemark.administrativeArea;
                }
                DLog(@"-----%@",city);
                self.locationCity = city;
                
            } else if ([placemarks count] == 0) {
                
                [UIAlertView alertWithCallBackBlock:^(NSInteger buttonIndex) {
                    ;
                } title:@"GPS故障" message:@"定位城市失败." cancelButtonName:@"确定" otherButtonTitles:nil, nil];
                
            }
        } else {
            //网络错误
        }
    }];
    [self.locationManager stopUpdatingLocation];
}

@end
